package com.fruit.controller.wap.goods;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.fruit.constants.GoodsContant;
import com.fruit.constants.RedisConstant;
import com.fruit.controller.base.BaseController;
import com.fruit.pojo.common.Page;
import com.fruit.pojo.goods.Base;
import com.fruit.pojo.goods.GoodsSpec;
import com.fruit.pojo.goods.GoodsSpecTime;
import com.fruit.pojo.goods.GoodsSpecTimeHarvest;
import com.fruit.pojo.recommend.Recommend;
import com.fruit.resolver.DefiniteException;
import com.fruit.service.goods.GoodsManager;
import com.fruit.service.recommend.RecommendManager;
import com.fruit.util.CommonUtil;
import com.fruit.util.DateUtil;
import com.fruit.util.ResultInfo;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * @ClassName: GoodsWapController
 * @author 葛欢欢
 * @version 2017.11.30 12:20
 */
@Slf4j
@Controller
@RequestMapping(value = "/wap/goods/")
public class GoodsWapController extends BaseController {

	@Autowired
	private GoodsManager goodsManager;

	@Autowired
	private RecommendManager recommendManager;

	@Value("${h5_domain}")
	private String h5Domain;

	/**
	 * 打开商品详情页面
	 * 
	 * @param request
	 *            request
	 * @param session
	 *            session
	 * @return ModelAndView
	 * @author 葛欢欢
	 * @version 2017.11.30 12:20
	 */
	@RequestMapping(value = "/detail", method = { RequestMethod.POST, RequestMethod.GET })
	public ModelAndView detail(HttpServletRequest request, HttpSession session) {
		long a = System.currentTimeMillis();
		log.info("【获取商品详情进入时间】" + DateUtil.getTime());
		log.info("【获取商品详情】---【开始】---");
		String goodsId = request.getParameter("id");
		log.info("【获取商品ID】---" + goodsId);
		if (StringUtils.isBlank(goodsId)) {
			throw new DefiniteException("商品id为空");
		}
		ModelAndView view = this.getModelAndView();
		List<GoodsSpecTime> goodsList = goodsManager.getGoodsDetail(Integer.parseInt(goodsId)); // 详情
		if (goodsList == null || goodsList.size() == 0) {
			throw new DefiniteException("商品不存在");
		} else {
			GoodsSpecTime goodsDetail = goodsList.get(0); // 详情
			log.info("【获取一条商品信息】---" + goodsDetail);
			if (goodsDetail.getSaleType().equals("00")) {// 以售馨
				goodsDetail.setStockNum(0);
			}
			List<GoodsSpecTimeHarvest> gsth = goodsManager.findGoodsSpecTimeHarvest(goodsDetail.getId());
			int harvestNum = 0;
			if (gsth != null && gsth.size() != 0) {
				harvestNum = gsth.size();
				for (int i = 0; i < gsth.size(); i++) {
					GoodsSpecTimeHarvest gsv = gsth.get(i);
					String harvesTimeStr = DateUtil.dateTimeToYYD(gsv.getExpectHarvestTime());
					gsv.setExpectHarvestTime(harvesTimeStr.substring(0, 8));
				}
			} else {
				harvestNum = 0;
			}
			String[] img = StringUtils.split(goodsDetail.getPicture(), ",");
			int imgNum = img.length;
			if (imgNum > 1) {
				view.addObject("img", img); // 图片
			} else {
				view.addObject("imgOne", img[0]); // 图片
			}
			Integer userId = (Integer) session.getAttribute("userId");
			log.info("【获取用户id】---" + userId);

			boolean dateB = DateUtil.compareDate(DateUtil.dTime(goodsDetail.getEndTime()), DateUtil.getDay());
			if (dateB) { // true 表示当前系统时间 小于 商品下架时间一样 （商品详情页面的 今日认养时间 为当前系统时间）
				view.addObject("date", DateUtil.getsdfDaymd());
			} else { // false 表示当前系统时间 大于等于 商品下架时间一样 （商品详情页面的 今日认养时间 为下架时间）
				view.addObject("date", DateUtil.dateTime(goodsDetail.getEndTime()));
			}
			view.addObject("goodsDetail", goodsDetail); // 商品详情
			view.addObject("imgNum", imgNum); // 图片数量
			view.addObject("shareImg", img[0]);
			view.addObject("userId", userId);
			view.addObject("goodsTimeId", goodsId);
			view.addObject("gsth", gsth); // 预计产量
			view.addObject("harvestNum", harvestNum); // 预计产量批数
			view.addObject("h5Domain", h5Domain); // 预计产量批数
			view.setViewName("good/detail");
		}
		log.info("【获取商品详情】---【结束】---");
		log.info("【获取商品详情耗时】" + (System.currentTimeMillis() - a) / 1000f + "秒");
		return view;
	}

	/**
	 * 打开商品规格列表
	 * 
	 * @param request
	 *            request
	 * @param session
	 *            session
	 * @return List<GoodsSpec>
	 * @author 葛欢欢
	 * @version 2017.11.30 12:20
	 */
	@RequestMapping(value = "/specList", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public List<GoodsSpec> specList(HttpServletRequest request, HttpSession session) {
		long a = System.currentTimeMillis();
		log.info("【获取商品详情进入时间】" + DateUtil.getTime());
		log.info("【此方法禁用------");
		String goodsId = request.getParameter("id");
		Map<String, Object> res = new HashMap<String, Object>();
		if (StringUtils.isBlank(goodsId)) {
			throw new DefiniteException("商品id为空");
		}
		List<GoodsSpec> goodsList = null; // goodsManager.getGoodsForSpec(Integer.parseInt(goodsId));//
											// 根据规则查询所有商品
		return goodsList;
	}

	/**
	 * 认养首页
	 * 
	 * @param request
	 *            request
	 * @param session
	 *            session
	 * @return Map<String, Object>
	 * @author 葛欢欢
	 * @version 2017.11.30 12:20
	 */
	@RequestMapping(value = "/getWapGoods", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public Map<String, Object> getWapGoods(String classId, Page page, HttpServletRequest request, HttpSession session) {
		long a = System.currentTimeMillis();
		log.info("【获取wap认养首页进入时间】" + DateUtil.getTime());
		log.info("【获取wap认养首页】---【开始】---");
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Map<String, Object> pam = new HashMap<String, Object>();
		Map<String, Object> recommendMap = new HashMap<String, Object>();
		String classString = null;
		if (StringUtils.isNotBlank(classId)) {
			classString = goodsManager.getClassIdByPid(classId);
		}
		pam.put("classId", classString); // 总的分类id
		pam.put("position", GoodsContant.SEASONAL); // 认养首页列表推荐
		pam.put("start", (page.getPage() - 1) * page.getShowNum());
		pam.put("num", page.getShowNum());
		try {
			recommendMap.put("classId", classId);
			recommendMap.put("type", "01");// wap版本
			// 认养大厅推荐位
			List<Recommend> recommendList = recommendManager.findRecommendByPosition(recommendMap);
			resultMap.put("recommendList", recommendList);
			resultMap.put("result", this.initResult(ResultInfo.SUCCESS, "ok", ""));

			// 获取商品列表
			List<GoodsSpec> goodsList = goodsManager.getGoodsList(pam); // 获取商品列表

			resultMap.put("goodsList", goodsList);
			resultMap.put("result", this.initResult(ResultInfo.SUCCESS, "ok", ""));
			// resultMap.put("allNum", goodsManager.getGoodSumNum());
		} catch (Exception e) {
			e.printStackTrace();
			resultMap.put("result", this.initResult(ResultInfo.ERROR, "exception", "系统异常"));
		}
		log.info("【获取wap认养首页】---【结束】---");
		log.info("【获取wap认养首页耗时】" + (System.currentTimeMillis() - a) / 1000f + "秒");
		return resultMap;
	}

	/**
	 * 认养大厅
	 * 
	 * @author 葛欢欢
	 * @version 2017.11.30 16:40
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getGoodsHall", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public Map<String, Object> getGoodsHall(HttpServletRequest request) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			log.info("【进入认养大厅】---【开始】---");
			resultMap = goodsManager.getGoodsHall("00");
			log.info("【进入认养大厅】---【结束】---");
		} catch (Exception e) {
			e.printStackTrace();
			log.info("【进入认养大厅】---【异常】---");
			resultMap.put("result", this.initResult(ResultInfo.ERROR, "exception", "系统异常"));
		}
		return resultMap;

	}

	/**
	 * 打开商品规格列表
	 * 
	 * @param request
	 *            request
	 * @param session
	 *            session
	 * @return List<GoodsSpec>
	 * @author 葛欢欢
	 * @version 2017.11.30 12:20
	 */
	@RequestMapping(value = "/baseInfo", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public Map<String, Object> getBaseInfo(HttpServletRequest request, HttpSession session) {
		long a = System.currentTimeMillis();
		log.info("【获取商品详情进入时间】" + DateUtil.getTime());
		log.info("【此方法禁用------");
		String baseId = request.getParameter("id");
		Map<String, Object> res = new HashMap<String, Object>();
		if (StringUtils.isBlank(baseId)) {
			res.put("result", this.initResult(ResultInfo.ERROR, "exception", "基地id位空"));
		} else {
			Base base = goodsManager.getBaseInfo(Integer.parseInt(baseId));
			res.put("base", base);
			res.put("result", this.initResult(ResultInfo.SUCCESS, "success", ""));
		}

		return res;
	}

}
